<?php
/**
 *
 * 消息查询接口
 * @author hebidu <hebiduhebi@126.com>
 * @date  15/12/5 10:28
 * @copyright by itboye.com
 */
namespace app\index\domain;

use app\admin\api\MessageApi;
use app\admin\model\Message;
use app\admin\api\MessageBoxApi;
use app\admin\api\SecurityCodeApi;
use app\admin\model\SecurityCode;
use app\index\domain\BaseDomain;
use app\system\api\UserApi;
use app\system\api\MemberApi;
use think\Hook;

class MessageDomain extends BaseDomain
{
    protected $business_code = "message";
    //调用阿里百川的消息服务
    //聚合SMS
    // const MSG_TYPE = "bai_chuan";
    const MSG_TYPE = "juhe_sms";

    //发送私信
    public function call(){
        $this->checkVersion($this->api_ver);
        addLog("Message/call", $_GET, $_POST,$this->client_id."调用用户私信接口");

        $uid     = $this->_post("uid",0,"uid不能为空!");
        $to_uid  = $this->_post("to_uid",0,"to_uid不能为空!");
        $content = $this->_post("message",'',"message不能为空!");
        $uid     = intval($uid);
        $to_uid  = intval($to_uid);
        if($uid == $to_uid) $this->apiReturnErr('不能给自己发送私信');
        $r = apiCall(MemberApi::GET_INFO,['`uid` ='.$to_uid]);
        if(!$r['status']) $this->apiReturnErr($r['info']);
        if(empty($r['info'])) $this->apiReturnErr('to_uid错误');
        $r = apiCall(MemberApi::GET_INFO,['`uid` ='.$uid]);
        if(!$r['status']) $this->apiReturnErr($r['info']);
        if(empty($r['info'])) $this->apiReturnErr('uid错误！');
        $nick = $r['info']['nickname'];
        // 发送消息
        // $msg_type = 6078; //私信消息
        // $entity = [
        // 'title'      =>'私信消息',
        // 'summary'    =>$nick.'给您发送了一条私信',
        // 'content'    =>trim($content),
        // 'to_id'      =>$to_uid,
        // 'dtree_type' =>$msg_type,
        // 'from_id'    =>$uid,
        // 'send_time'  =>NOW_TIME,
        // 'status'     =>1,
        // 'extra'      =>'',
        // ];
        // $r = apiCall(MessageApi::RECORD_MESSAGE,[$entity,true]);
        // 推送消息
        $entity = [
            'from_id' =>$uid,
            'title'   =>Message::MESSAGE_CALL,
            'content' =>trim($content),
            'summary' =>$nick.'给您发了一条私信',
            'extra'   =>'', //消息记录中的
        ];
        $after_open = ['type'=>'go_activity','param'=>Message::MESSAGE_CALL_ACTIVITY,'extra'=>['uid'=>$uid,'nickname'=>$nick]]; //推送参数
        $r = apiCall(MessageApi::PUSH_MESSAGE_WITH_TYPE,[Message::MESSAGE_CALL,$entity,$to_uid,false,$after_open]);
        if($r['status']) $this->apiReturnSuc('发送成功');
        else $this->apiReturnSuc($r['info']);
    }
    //查阅信息 - 修改信息为已读
    public function read(){
        $this->checkVersion($this->api_ver);
        addLog("Message/read", $_GET, $_POST,$this->client_id."调用信息已读接口");
        $uid = $this->_post("uid",0,"uid不能为空!");
        $id  = $this->_post("id",0,"id不能为空!");
        $r = apiCall(MessageBoxApi::SAVE,[['to_id'=>$uid,'msg_id'=>$id],['msg_status'=>1]]);
        if(!$r['status']) $this->apiReturnErr($r['info']);
        if(empty($r['info'])) $this->apiReturnErr('该用户无此消息');
        $this->apiReturnSuc('已读成功');
    }
    //推送系统消息测试 - 未打开自动页面
    public function system(){
        $this->checkVersion($this->api_ver);
        addLog("Message/system", $_GET, $_POST,$this->client_id."调用系统信息推送接口");
        $uid = intval($this->_post("uid",0));
        $msg = $this->_post("msg",'',"不能为空!");
        // 推送系统消息
        $entity = [
            'from_id' =>0,
            'title'   =>Message::MESSAGE_SYSTEM,
            'content' =>trim($msg),
            'summary' =>'系统消息',
            'extra'   =>'', //消息记录中的
        ];
        $after_open = ['type'=>'go_activity','param'=>Message::MESSAGE_SYSTEM_ACTIVITY,'extra'=>[]];
        if($uid) $pushAll = false;
        else $pushAll = true;
        $r = apiCall(MessageApi::PUSH_MESSAGE_WITH_TYPE,[Message::MESSAGE_SYSTEM,$entity,$uid,$pushAll,$after_open]);

        if(!$r['status']) $this->apiReturnErr($r['info']);
        else $this->apiReturnSuc($r['info']);
    }
    //删除私信 2人间
    public function deleteCall(){
        $this->checkVersion(100);
        addLog("Message/deleteCall", $_GET, $_POST,$this->client_id."调用信息删除接口");
        $curr_uid = $this->_post("curr_uid",'',"current uid不能为空!");
        $rela_uid = $this->_post("rela_uid",'',"relation uid不能为空!");
        $model = new \think\model\Adv();
        $model ->startTrans();
        $r = apiCall(MessageApi::SAVE_WITH_BOX,[$curr_uid,$rela_uid]);
        if(!$r['status']){
            $model->rollback();
            $this->apiReturnErr($r['info']);
        }
        $model->commit();
        $this ->apiReturnSuc($r['info']);
    }
    //删除信息
    public function delete(){
        $this->checkVersion(101);
        addLog("Message/delete", $_GET, $_POST,$this->client_id."调用信息删除接口");
        $uid = $this->_post("uid",0,"uid不能为空!");
        $ids = $this->_post("ids",0,"ids不能为空!");
        //查询
        $ids = explode(',', $ids);
        $model = new \think\model\Adv();
        //开启事务
        $model ->startTrans();
        foreach ($ids as $id) {
            $r = apiCall(MessageApi::GET_INFO_WITH_BOX,[['m.id'=>$id],false,'m.*,mb.msg_status,mb.to_id']);
            if(!$r['status']){
                $model ->rollback();
                $this->apiReturnErr($r['info']);
            }
            if(empty($r['info'])){
                $model ->rollback();
                $this->apiReturnErr('id错误');
            }
            if(6078 == intval($r['info']['dtree_type'])){
                //删除私信
                if($uid == $r['info']['to_id']){
                    if(2 == $r['info']['msg_status']){
                        $model->rollback();
                        $this->apiReturnErr('该私信已删除');
                    }
                    //接收者删除私信 - 修改msg_status
                    $r = apiCall(MessageBoxApi::SAVE,[['msg_id'=>$id],['msg_status'=>2]]);
                    if(!$r['status']){
                        $model->rollback();
                        $this->apiReturnErr($r['info']);
                    }
                    // $this->apiReturnSuc('删除成功');
                }elseif($uid == $r['info']['from_id']){
                    if(-1 == $r['info']['status']){
                        $model->rollback();
                        $this->apiReturnErr('该私信已删除');
                    }
                    //发送者删除私信 - 修改status
                    $r = apiCall(MessageApi::SAVE,[['id'=>$id],['status'=>-1]]);
                    if(!$r['status']){
                        $model->rollback();
                        $this->apiReturnErr($r['info']);
                    }
                    // $this->apiReturnSuc('删除成功');
                }
            }else{
                //删除个人信息
                if(intval($uid) !== intval($r['info']['to_id'])){
                    $model->rollback();
                    $this->apiReturnErr('uid错误');
                }
                $r = apiCall(MessageBoxApi::SAVE,[['to_id'=>$uid,'msg_id'=>$id],['msg_status'=>2]]);
                if(!$r['status']){
                    $model ->rollback();
                    $this->apiReturnErr($r['info']);
                }
                // if(empty($r['info'])) $this->apiReturnErr('msg_id或uid错误');
                $r = apiCall(MessageApi::SAVE,[['id'=>$id],['status'=>-1]]);
                if(!$r['status']){
                    $model ->rollback();
                    $this->apiReturnErr($r['info']);

                }
            }
        }
        $model ->commit();
        $this ->apiReturnSuc('删除成功');
    }
    /**
     * 发送短消息
     */
    public function send_sms()
    {
        $this->checkVersion($this->api_ver);
        $mobile = $this->_post("mobile","","手机号不能为空!");
        if(!preg_match('/^1\d{10}$/', $mobile)) $this->apiReturnErr("手机格式错误!");;
        $type   = $this->_post("code_type","","code_type参数不能为空!");
        $notes  = $this->getTypeDesc($type);

        // trace('notes:'.$notes);
        addLog("Message/send", $_GET, $_POST,$this->client_id."用于".$notes.",发送了验证码");

        $map = ['accepter' => $mobile,'type'=>intval($type)];

        $result = apiCall(SecurityCodeApi::GET_INFO, [$map,"starttime desc"]);
        // $this->apiReturnErr($result);//bug

//        if($result['status'] && $result['info']){
//            $info = $result['info'];
//            if($info['starttime'] <  NOW_TIME && $info['starttime'] + 60*1 > NOW_TIME  ){
//                //1分钟内只能向一个手机发一次信息
//                $delay = 60*1  + $info['starttime'] - NOW_TIME;
//
//                $this->apiReturnErr("请在".$delay."秒后再试!");
//            }
//        }

        //TODO: 考虑移走，不应该放这里检测
        $this->mobileCheck($mobile,$type);

        //生成短信验证码6位
        $code = mt_rand(100000, 999999);



        //2. 纪录到数据库
        $entity = array(
            'code'      => $code,
            'accepter'  => $mobile,
            'starttime' => time(),
            'endtime'   => time() + 1800,
            'ip'        => ip2long(get_client_ip()),
            'client_id' => $this->client_id,
            'type'      =>$type,
            'status'    =>0,// 未验证
        );

        $result = apiCall(SecurityCodeApi::ADD, array($entity));

        if (!$result['status']) {
            LogRecord($result['info'], __FILE__ . __LINE__);
            $this->apiReturnErr($result['info']);
        }

        //以下测试时注释不发短信
        //1. 发送短信
        $result = $this->send_msg($code,$mobile,$type);
        // if (!$result['status']) {
        //     $this->apiReturnErr($result['info']);
        // }else{
        //     $code = $result['info'];
        // }
        //以上测试时注释 不发短信
        //测试时返回验证码
//         $code = "短信已发送，请注意查看!";
        $this->apiReturnSuc($code);
    }

    /*
     * 验证码验证
     */
    public function checkCode()
    {
        $this->checkVersion($this->api_ver);
        $code   =$this->_post('code','','缺少code参数');
        $mobile =$this->_post('mobile','','缺少mobile参数');
        $type   = $this->_post('code_type','','缺少type参数');

        $note = $this->getTypeDesc($type);

        addLog("Message/checkCode", $_GET, $_POST,"用户".$mobile."用于".$note.",验证验证码");

        $result = apiCall(SecurityCodeApi::IS_LEGAL_CODE,array($code,$mobile,$type));

        if($result['status']){
            $this->apiReturnSuc("验证通过!");
        }else{
            $this->apiReturnErr("验证失败!");
        }

    }
    //2人间私信详情
    public function detailCall(){
        if(IS_POST){
            $this->checkVersion($this->api_ver);
            $notes = "应用" . $this->client_id . "调用用户私信查询接口";
            addLog("Message/detailCall", $_GET, $_POST, $notes);

            $curr_uid   = $this->_post('curr_uid','','curr uid缺失');
            $rela_uid   = $this->_post('rela_uid','','rela uid缺失');
            $start_time = $this->_post('start_time','');
            $page_no    = $this->_post('page_no',0);
            $page_size  = $this->_post('page_size',10);
            $map  = [];
            $map  = ['curr_uid'=> $curr_uid,'rela_uid'=> $rela_uid];
            if($start_time) $map['start_time'] = $start_time;
            $page = ['curpage'=>$page_no,'size'=>$page_size];
            $result = apiCall(MessageApi::QUERY_DETAIL_CALL_WITH_COUNT,[$map,$page]);
            if ($result['status']) {
                $userInfo = [];
                foreach ($result['info']['list'] as &$v) {
                    $uid = $v['from_id'];
                    if(!isset($userInfo[$uid])) $userInfo[$uid] = $this->getUserInfo($uid);
                    $v['from_nick'] = empty($userInfo[$uid]) ? '' : $userInfo[$uid]['nickname'];
                    $v['from_head'] = empty($userInfo[$uid]) ? '' : $userInfo[$uid]['head'];
                    $v['from_sex']  = empty($userInfo[$uid]) ? '' : $userInfo[$uid]['sex'];
                    $uid = $v['to_id'];
                    if(!isset($userInfo[$uid])) $userInfo[$uid] = $this->getUserInfo($uid);
                    $v['to_nick'] = empty($userInfo[$uid]) ? '' : $userInfo[$uid]['nickname'];
                    $v['to_head'] = empty($userInfo[$uid]) ? '' : $userInfo[$uid]['head'];
                    $v['to_sex']  = empty($userInfo[$uid]) ? '' : $userInfo[$uid]['sex'];
                }
                unset($userInfo);
                $this->apiReturnSuc($result['info']);
            } else {
               $this->apiReturnErr($result['info']);
            }
        }
    }
    /**
     * 用户私信分页查询 - group by 时间不对
     */
    public function queryCall(){
        if(IS_POST){
            $uid        = $this->_post('uid','','用户UID缺失');
            $start_time = $this->_post('start_time','');
            $page_no    = $this->_post('page_no',1);
            $page_size  = $this->_post('page_size',10);

            $this->checkVersion($this->api_ver);
            $notes = "应用" . $this->client_id . ":[用户" . $uid . "],调用用户私信查询接口,消息时间:".$start_time;
            addLog("Message/queryCall", $_GET, $_POST, $notes);

            $map  = ['uid'=> $uid];
            if($start_time) $map['start_time'] = $start_time;
            $page = ['curpage'=>$page_no,'size'=>$page_size];
            $result = apiCall(MessageApi::QUERY_CALL_WITH_COUNT,[$map,$page]);
            if ($result['status']) {
                $userInfo = [];
                foreach ($result['info']['list'] as &$v) {
                    $uid = $v['from_id'];
                    if(!isset($userInfo[$uid])) $userInfo[$uid] = $this->getUserInfo($uid);
                    $v['from_nick'] = empty($userInfo[$uid]) ? '' : $userInfo[$uid]['nickname'];
                    $v['from_head'] = empty($userInfo[$uid]) ? '' : $userInfo[$uid]['head'];
                    $v['from_sex']  = empty($userInfo[$uid]) ? '' : $userInfo[$uid]['sex'];
                    $uid = $v['to_id'];
                    if(!isset($userInfo[$uid])) $userInfo[$uid] = $this->getUserInfo($uid);
                    $v['to_nick'] = empty($userInfo[$uid]) ? '' : $userInfo[$uid]['nickname'];
                    $v['to_head'] = empty($userInfo[$uid]) ? '' : $userInfo[$uid]['head'];
                    $v['to_sex']  = empty($userInfo[$uid]) ? '' : $userInfo[$uid]['sex'];
                }
                unset($userInfo);
               $this->apiReturnSuc($result['info']);
            } else {
               $this->apiReturnErr($result['info']);
            }
        }

    }
    /**
     * 消息分页查询
     */
    public function query(){
        if(IS_POST){
            $uid        = $this->_post('uid','');
            $msg_type   = $this->_post('msg_type','','消息类型缺失');
            $start_time = $this->_post('start_time',0);
            $page_no    = $this->_post('page_no',1);
            $page_size  = $this->_post('page_size',10);

            $this->checkVersion($this->api_ver);
            $notes = "应用" . $this->client_id . ":[用户" . $uid . "],调用消息查询接口,消息时间:".$start_time;
            addLog("Message/query", $_GET, $_POST, $notes);
            $msg_type = intval($msg_type);
            if(!in_array($msg_type, [1,2,3,4,5])) $this->apiReturnErr('msg_type非法');
            //非系统消息 需要uid
            if($msg_type !== 1 && !$uid) $this->apiReturnErr('需要uid');
            // $result = apiCall(MessageApi::QUERY_BY_UID,[$uid,$msg_type,$start_time]);
            $map  = [
                // 'uid'        => $uid,
                'msg_type'   => $msg_type,
                'start_time' => $start_time,
            ];
            if($uid) $map['uid'] = $uid;
            $page = ['curpage'=>$page_no,'size'=>$page_size];
            $result = apiCall(MessageApi::QUERY_WITH_COUNT,[$map,$page]);
            if ($result['status']) {
                $this->apiReturnSuc($result['info']);
            } else {
                $this->apiReturnErr($result['info']);
            }
        }

    }


    //****************************私有*************************************************//

    private function mobileCheck($mobile,$type){
        $map = ['mobile' => $mobile];

        $result = apiCall(UserApi::FIND, array($map));

        if($type == SecurityCode::TYPE_FOR_REGISTER){
            if ($result['info'] != null) {
                $this->apiReturnErr("该手机号已注册!");
            }
        }elseif($type == SecurityCode::TYPE_FOR_UPDATE_PSW ){
            if ($result['info'] == null) {
                $this->apiReturnErr("该手机号未注册!");
            }
        }
    }


    private function getTypeDesc($type){

        switch($type){
            case SecurityCode::TYPE_FOR_CHANGE_NEW_PHONE:
                return "更换手机";
            case SecurityCode::TYPE_FOR_NEW_BIND_PHONE:
                return "绑定新手机";
            case SecurityCode::TYPE_FOR_REGISTER:
                return "注册";
            case SecurityCode::TYPE_FOR_UPDATE_PSW:
                return "更新密码";
            case SecurityCode::TYPE_FOR_BIND_ALIPAY:
                return "绑定支付宝账号";
            default:
                return "未知";
        }
    }

    //发送短信
    private function send_msg($code,$mobile,$type){

        switch($type){
            case SecurityCode::TYPE_FOR_CHANGE_NEW_PHONE:
                $domain_text = "更换手机";
                $type_desc = "change_phone";
                break;
            case SecurityCode::TYPE_FOR_NEW_BIND_PHONE:
                $domain_text = "绑定新手机";
                $type_desc = "new_phone";
                break;
            case SecurityCode::TYPE_FOR_REGISTER:
                $domain_text = "注册";
                $type_desc = "register";
                break;
            case SecurityCode::TYPE_FOR_UPDATE_PSW:
                $domain_text = "更新密码";
                $type_desc = "update_password";
                break;
            default:
                $domain_text = "未知";
                $type_desc = "unknown";
                break;
        }
        $params = [
            'domain_text' =>$domain_text,
            'domain'      =>$type_desc,
            'code'        =>$code,
            'mobile'      =>$mobile,
        ];

        Hook::listen("boye_api_message_send",$params);

        return $params;
    }

    /**
     * 查询用户主体信息
     */
    private function getUserInfo($uid){
        //$result = apiCall('Api/BbsUserCenter/userInfo',array($uid),'Domain');
        $result = apiCall(MemberApi::GET_INFO,[['uid'=>$uid]]);
        if($result['status'] && $result['info']){
            return $result['info'];
        }else{
            return [];//$this->apiReturnErr('查询用户信息失败');
        }
    }
}